package org.example.websocket;

import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
@ServerEndpoint("/webSocket/{oid}")
public class WebSocketService {

    //将所有订单的编号对应前端反馈记录下来
    private static Map<String, Session> sessionMap = new ConcurrentHashMap<>();

    @OnOpen
    //WebSocket连接建立成功调用此方法
    public void open(@PathParam("oid") String orderId, Session session){
        System.out.println("open \t  orderId = " + orderId);
        sessionMap.put(orderId, session);
    }

    @OnClose
    //WebSocket连接销毁成功调用此方法
    public void close(@PathParam("oid") String orderId){
        System.out.println("close \t  orderId = " + orderId);
        sessionMap.remove(orderId);
    }

    //支付成功后给前端反馈对应参数
    public static void sendMsg(String orderId, String msg){
        try {
            System.out.print("sendMsg" + "\t");
            System.out.println(sessionMap);
            Session session = sessionMap.get(orderId);
            session.getBasicRemote().sendText(msg);
        }catch (Exception e){
            e.printStackTrace();
        }

    }

}
